﻿Imports System.Xml
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration


Public Class frmThietBi_Tram
    Private components As System.ComponentModel.IContainer = New System.ComponentModel.Container
    Friend WithEvents ThietBiDataSet As ThietBiDataSet = New ThietBiDataSet
    'ThietBi_Tram
    Friend WithEvents THIETBITRAMBindingSource As System.Windows.Forms.BindingSource = New System.Windows.Forms.BindingSource(Me.components)
    Friend WithEvents THIETBI_TRAMTableAdapter As ThietBiDataSetTableAdapters.THIETBI_TRAMTableAdapter = New ThietBiDataSetTableAdapters.THIETBI_TRAMTableAdapter
    'ThietBi
    Friend WithEvents THIETBIBindingSource As System.Windows.Forms.BindingSource = New System.Windows.Forms.BindingSource(Me.components)
    Friend WithEvents THIETBITableAdapter As ThietBiDataSetTableAdapters.THIETBITableAdapter = New ThietBiDataSetTableAdapters.THIETBITableAdapter
    'DonVi
    Friend WithEvents DONVIBindingSource As System.Windows.Forms.BindingSource = New System.Windows.Forms.BindingSource(Me.components)
    Friend WithEvents DONVITableAdapter As ThietBiDataSetTableAdapters.DONVITableAdapter = New ThietBiDataSetTableAdapters.DONVITableAdapter

    'Properties
    Private _columnDict As Dictionary(Of String, DataGridViewColumn) = New Dictionary(Of String, DataGridViewColumn)
    Private _tramId As Integer = 33 'Init value
    Private _currMaThietBi As String = "00" 'Init value

    Public Sub InitThietBiDataSet()
        '
        'ThietBiDataSet
        '
        Me.ThietBiDataSet.DataSetName = "ThietBiDataSet"
        Me.ThietBiDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema

        '
        'THIETBITRAMBindingSource
        '
        Me.THIETBITRAMBindingSource.DataMember = "THIETBI_TRAM"
        Me.THIETBITRAMBindingSource.DataSource = Me.ThietBiDataSet

        '
        'DONVIBindingSource
        '
        Me.DONVIBindingSource.DataMember = "DONVI"
        Me.DONVIBindingSource.DataSource = Me.ThietBiDataSet

        '
        'THIETBIBindingSource
        '
        Me.THIETBIBindingSource.DataMember = "THIETBI"
        Me.THIETBIBindingSource.DataSource = Me.ThietBiDataSet

        '
        'THIETBI_TRAMTableAdapter
        '
        Me.THIETBI_TRAMTableAdapter.ClearBeforeFill = True
        '
        'THIETBITableAdapter
        '
        Me.THIETBITableAdapter.ClearBeforeFill = True
        '
        'DONVITableAdapter
        '
        Me.DONVITableAdapter.ClearBeforeFill = True
    End Sub

    Private loaiThietBiDict As Dictionary(Of String, String) = New Dictionary(Of String, String)
    Private Sub frmThietBi_Tram_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Read configuration
        For Each key As String In Configuration.ConfigurationSettings.AppSettings.Keys
            loaiThietBiDict.Add(key, Configuration.ConfigurationSettings.AppSettings(key))
        Next

        'Init DataSet
        InitThietBiDataSet()

        'TODO: This line of code loads data into the 'ThietBiDataSet.DONVI' table. You can move, or remove it, as needed.
        Me.DONVITableAdapter.Fill(Me.ThietBiDataSet.DONVI)
        'TODO: This line of code loads data into the 'ThietBiDataSet.THIETBI' table. You can move, or remove it, as needed.
        Me.THIETBITableAdapter.Fill(Me.ThietBiDataSet.THIETBI)
        'TODO: This line of code loads data into the 'ThietBiDataSet.THIETBI_TRAM' table. You can move, or remove it, as needed.
        Me.THIETBI_TRAMTableAdapter.Fill(Me.ThietBiDataSet.THIETBI_TRAM)

        'Title form
        Me.Text = String.Format("Danh mục các Thiết bị của Trạm {0}", _tramId.ToString())

        'Load datagridview
        Me.DataGridViewThietBi_Tram.DataSource = Me.THIETBITRAMBindingSource

        'Format datagridview
        FormatDataGridView()

        'Save columns into dictionary
        For Each column As DataGridViewColumn In DataGridViewThietBi_Tram.Columns
            Dim textBoxColumn As DataGridViewColumn = CType(column, DataGridViewColumn)
            _columnDict.Add(textBoxColumn.Name, textBoxColumn)
        Next

        'TreeView
        LoadTreeView()
    End Sub

    'Private xmlDataGridView As XmlDocument

    Public Sub LoadTreeView()
        Me.DBiTraDM1.ConnStr = myConnStr
        Me.DBiTraDM1.UserID = g_UserID
        Me.DBiTraDM1.Password = g_Password
        Me.DBiTraDM1.TableName = "ThietBi"
        Me.DBiTraDM1.MaFieldName = "MaThietBi"
        Me.DBiTraDM1.TenFieldName = "TenThietBi"
        Me.DBiTraDM1.CuoiFieldName = "Cuoi"
        Me.DBiTraDM1.IDFieldName = "ThietBi_ID"
        'Me.DBiTraDM1.DMIDFieldName = "DienBien_ID"
        'Me.DBiTraDM1.DMIDValue = mDienBien_ID
        Me.DBiTraDM1.MnuChonText = ""
        Me.DBiTraDM1.KhoiDong(0)
    End Sub

    Public Sub FormatDataGridView()
        'Change column name same DataPropertyName
        For Each column As DataGridViewColumn In DataGridViewThietBi_Tram.Columns
            column.Name = column.DataPropertyName
        Next

        With DataGridViewThietBi_Tram
            'General information
            .ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.False
            .BorderStyle = BorderStyle.Fixed3D
            .AllowUserToResizeRows = False
            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells ' DataGridViewAutoSizeColumnsMode.None

            'Frozen
            .Columns("THIETBI_TRAM_ID").Frozen = True
            .Columns("TRAM_ID").Frozen = True
            '.Columns("THIETBI_ID").Frozen = True

            'Title
            .Columns("DIADANH").HeaderText = "Địa danh"
            .Columns("NGAYKT").HeaderText = "Ngày khai thác"
            .Columns("DIENTHOAI").HeaderText = "Điện thoại"
            .Columns("GHICHU").HeaderText = "Ghi chú"
            .Columns("DUNGLUONG_MAX").HeaderText = "DL Max"
            .Columns("DUNGLUONG_HIENTAI").HeaderText = "DL Hiện tại"
            .Columns("DUNGLUONG_KETNOI").HeaderText = "DL Kết nối"
            .Columns("DUNGLUONG_THUEBAO").HeaderText = "DL Thuê bao"
            .Columns("DLSD_BTL").HeaderText = "DL BTL"
            .Columns("DLSD_DONVI").HeaderText = "DL Đơn vị"
            .Columns("DLSD_VTEL").HeaderText = "DL VTEL"
            .Columns("DLSD_KHAC").HeaderText = "DL Khác"
            .Columns("TSL_MAX").HeaderText = "TSL max"
            .Columns("TSL_HIENTAI").HeaderText = "TSL Hiện tại"
            .Columns("ANTEN_LOAICOT").HeaderText = "Anten Loại cột"
            .Columns("ANTEN_DOCAO").HeaderText = "Anten Độ cao"
            .Columns("ANTEN_PHANCUC").HeaderText = "Anten Phân cực"
            .Columns("TANSO_THU").HeaderText = "Tần số thu"
            .Columns("TANSO_PHAT").HeaderText = "Tần số phát"
            '==================================================================
            'VSAT,OPTIMUX
            .Columns("KETNOI").HeaderText = "Kết nối"
            .Columns("DUNGLUONG").HeaderText = "Dung lượng"
            '==================================================================
            'Tổng đài
            .Columns("QUYSO").HeaderText = "Quỹ số"
            .Columns("HUONG_KET_NOI").HeaderText = "Hướng kết nối"
            .Columns("KHU_VUC_QUAN_LY").HeaderText = "Khu vực quản lý"
            '==================================================================
            'Truyền số liệu
            .Columns("DL_STM_MAX").HeaderText = "STM Max"
            .Columns("DL_STM_SD").HeaderText = "STM SD"
            .Columns("DL_E1_MAX").HeaderText = "E1 Max"
            .Columns("DL_E1_SD").HeaderText = "E1 SD"
            .Columns("DL_E2_MAX").HeaderText = "E2 Max"
            .Columns("DL_E2_SD").HeaderText = "E2 SD"
            .Columns("DL_E3_MAX").HeaderText = "E3 Max"
            .Columns("DL_E3_SD").HeaderText = "E3 SD"
            .Columns("DIACHI_IP").HeaderText = "Địa chỉ IP"
        End With
        'Add combobox ThietBi
        AddComboBoxColumns_ThietBi()
        'Add combobox DonVi
        AddComboBoxColumns_DVQL()

        AddDateTimePickerColumns_NgayKT()
    End Sub

    ''' <summary>
    ''' Show hide columns by ThietBi_Id
    ''' </summary>
    ''' <param name="MaThietBi"></param>
    ''' <remarks></remarks>
    Public Sub ShowHideColumns(ByVal MaThietBi As String)
        Dim columns As String
        Select Case MaThietBi.Substring(0, 2)
            'Case "01" 'Cáp quang
            '    columns = "THIETBI_ID, DUNGLUONG_MAX, DUNGLUONG_HIENTAI, DLSD_BTL, DLSD_VTEL, DLSD_KHAC, DVQL_ID, NGAYKT, DIADANH, DIENTHOAI, GHICHU"
            'Case "02" 'Viba
            '    columns = "THIETBI_ID, TSL_MAX, TSL_HIENTAI, ANTEN_LOAICOT, ANTEN_DOCAO, ANTEN_PHANCUC, TANSO_THU, TANSO_PHAT, DVQL_ID, DIADANH, DIENTHOAI, GHICHU"
            'Case "03" 'Tổng đài
            '    columns = "THIETBI_ID, KETNOI, DUNGLUONG, DVQL_ID, NGAYKT, DIADANH, DIENTHOAI, GHICHU"
            'Case "04", "05" 'HDSL
            '    columns = "THIETBI_ID, DUNGLUONG_MAX, DLSD_DONVI, DLSD_VTEL, DLSD_KHAC, DVQL_ID, NGAYKT, DIADANH, DIENTHOAI, GHICHU"
            'Case Else 'Các thiết bị khác
            '    columns = "THIETBI_ID, DL_STM_MAX, DL_STM_SD, DL_E3_MAX, DL_E3_SD, DL_E2_MAX, DL_E2_SD, DL_E1_MAX, DL_E1_SD, DIACHI_IP, DVQL_ID, NGAYKT, DIADANH, DIENTHOAI, GHICHU"

            Case loaiThietBiDict("CapQuang")
                columns = "THIETBI_ID, DUNGLUONG_MAX, DUNGLUONG_HIENTAI, DLSD_BTL, DLSD_VTEL, DLSD_KHAC, DVQL_ID, NGAYKT, DIADANH, DIENTHOAI, GHICHU"
            Case loaiThietBiDict("Viba")
                columns = "THIETBI_ID, TSL_MAX, TSL_HIENTAI, ANTEN_LOAICOT, ANTEN_DOCAO, ANTEN_PHANCUC, TANSO_THU, TANSO_PHAT, DVQL_ID, DIADANH, DIENTHOAI, GHICHU"
            Case loaiThietBiDict("VSAT")
                columns = "THIETBI_ID, KETNOI, DUNGLUONG, DVQL_ID, NGAYKT, DIADANH, DIENTHOAI, GHICHU"
            Case loaiThietBiDict("HDSL"), loaiThietBiDict("Optimux")
                columns = "THIETBI_ID, DUNGLUONG_MAX, DLSD_DONVI, DLSD_VTEL, DLSD_KHAC, DVQL_ID, NGAYKT, DIADANH, DIENTHOAI, GHICHU"
            Case loaiThietBiDict("TruyenSoLieu")
                columns = "THIETBI_ID, DL_STM_MAX, DL_STM_SD, DL_E3_MAX, DL_E3_SD, DL_E2_MAX, DL_E2_SD, DL_E1_MAX, DL_E1_SD, DIACHI_IP, DVQL_ID, NGAYKT, DIADANH, DIENTHOAI, GHICHU"
            Case loaiThietBiDict("TongDai")
                columns = "THIETBI_ID, DL_STM_MAX, DL_STM_SD, DL_E3_MAX, DL_E3_SD, DL_E2_MAX, DL_E2_SD, DL_E1_MAX, DL_E1_SD, DIACHI_IP, DVQL_ID, NGAYKT, DIADANH, DIENTHOAI, GHICHU"
            Case Else 'Các thiết bị khác
                columns = "THIETBI_ID, DVQL_ID, NGAYKT, DIADANH, DIENTHOAI, GHICHU"
        End Select
        columns = columns.Replace(" ", "")

        Dim split As String() = columns.Split(New [Char]() {","c})
        For Each r As DataGridViewColumn In DataGridViewThietBi_Tram.Columns
            r.Visible = False
        Next

        'Visible and order columns
        For i As Integer = 0 To split.Length - 1
            'DataGridViewThietBi_Tram.Columns.Add(columnDict(split(i)))
            DataGridViewThietBi_Tram.Columns(split(i)).Visible = True
            DataGridViewThietBi_Tram.Columns(split(i)).DisplayIndex = i
        Next
    End Sub

    'Ham nay dung de thay the MaKho textbox column thanh combobox column
    Private Sub AddComboBoxColumns_ThietBi()
        Dim comboboxColumn As New DataGridViewComboBoxColumn()
        Dim colName As String = "THIETBI_ID"
        With comboboxColumn
            .Name = colName
            .ReadOnly = True
            .Frozen = True
            .DataPropertyName = colName
            .HeaderText = "Thiết bị"
            .FlatStyle = FlatStyle.Flat
            .DropDownWidth = 150
            .Width = DataGridViewThietBi_Tram.Columns(colName).Width
            .DataSource = THIETBIBindingSource
            .ValueMember = "THIETBI_ID"
            .DisplayMember = "TENTHIETBI"
            .DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
        End With
        Try
            Dim index As Integer = DataGridViewThietBi_Tram.Columns(colName).Index
            DataGridViewThietBi_Tram.Columns.Remove(colName)
            DataGridViewThietBi_Tram.Columns.Insert(index, comboboxColumn)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    'Ham nay dung de thay the MaKho textbox column thanh combobox column
    Private Sub AddDateTimePickerColumns_NgayKT()
        Dim calendarColumn As New CalendarColumn()
        Dim colName As String = "NGAYKT"
        With calendarColumn
            .Name = colName
            '.Frozen = True
            .DataPropertyName = colName
            .HeaderText = "Ngày khai thác"
            .Width = DataGridViewThietBi_Tram.Columns(colName).Width
            '.DataSource = DONVIBindingSource
            '.ValueMember = "DONVI_ID"
            '.DisplayMember = "TENDONVI"
            '.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
        End With
        Try
            Dim index As Integer = DataGridViewThietBi_Tram.Columns(colName).Index
            DataGridViewThietBi_Tram.Columns.Remove(colName)
            DataGridViewThietBi_Tram.Columns.Insert(index, calendarColumn)
            'DataGridViewThietBi_Tram.Columns.Add(calendarColumn)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    'Ham nay dung de thay the MaKho textbox column thanh combobox column
    Private Sub AddComboBoxColumns_DVQL()
        Dim comboboxColumn As New DataGridViewComboBoxColumn()
        Dim colName As String = "DVQL_ID"
        With comboboxColumn
            .Name = colName
            '.Frozen = True
            .DataPropertyName = colName
            .HeaderText = "Đơn vị QL"
            .FlatStyle = FlatStyle.Flat
            .DropDownWidth = 150
            .Width = DataGridViewThietBi_Tram.Columns(colName).Width
            .DataSource = DONVIBindingSource
            .ValueMember = "DONVI_ID"
            .DisplayMember = "TENDONVI"
            .DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
            .ReadOnly = True
        End With
        Try
            Dim index As Integer = DataGridViewThietBi_Tram.Columns(colName).Index
            DataGridViewThietBi_Tram.Columns.Remove(colName)
            DataGridViewThietBi_Tram.Columns.Insert(index, comboboxColumn)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub


    Private Sub DBiTraDM1_OnSelect(ByVal TxtValue As System.String, ByVal MaValue As System.String) Handles DBiTraDM1.OnSelect
        Dim sql As String = String.Format("select * from ThietBi_Tram where Tram_Id = {0} and ThietBi_Id in (select ThietBi_Id from ThietBi where left(MATHIETBI,len('{1}')) = '{2}')", _tramId, MaValue, MaValue)
        THIETBI_TRAMTableAdapter.FillByQuery(Me.ThietBiDataSet.THIETBI_TRAM, sql)
        If _currMaThietBi.Substring(0, 2) <> MaValue.Substring(0, 2) Then
            ShowHideColumns(MaValue)
        End If
        _currMaThietBi = MaValue
    End Sub

    Private Sub DBiTraDM1_DaChon(ByVal IdValue As System.Int64, ByVal TxtValue As System.String, ByVal MaValue As System.String) Handles DBiTraDM1.DaChon
        'If MaValue = "" Then
        '    Exit Sub
        'End If
        'If MessageBox.Show("Muốn thêm Thiết bị này?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
        '    Dim sql As String = String.Format("select THIETBI_ID from THIETBI where MATHIETBI = '{0}'", MaValue)
        '    Dim thietbi_id As Object = MITI.BaseDB.ExecSql_DataValue(sql)
        '    Dim objThietBi_TramRow As ThietBiDataSet.THIETBI_TRAMRow = Me.ThietBiDataSet.THIETBI_TRAM.NewTHIETBI_TRAMRow()
        '    objThietBi_TramRow.THIETBI_ID = CType(thietbi_id, Integer)
        '    objThietBi_TramRow.TRAM_ID = _tramId
        '    ThietBiDataSet.THIETBI_TRAM.AddTHIETBI_TRAMRow(objThietBi_TramRow)
        '    THIETBITRAMBindingSource.EndEdit()
        '    THIETBI_TRAMTableAdapter.Update(ThietBiDataSet.THIETBI_TRAM)
        'End If
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        THIETBITRAMBindingSource.EndEdit()
        THIETBI_TRAMTableAdapter.Update(ThietBiDataSet.THIETBI_TRAM)
        MessageBox.Show("Cập nhật xong.")
    End Sub

    Private Sub btnAddNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddNew.Click
        If _currMaThietBi = "" Then
            Exit Sub
        End If
        'If MessageBox.Show(string.Format("Muốn thêm thiết bị {0} này?",, "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
        If MessageBox.Show("Muốn thêm thiết bị này?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
            Dim sql As String = String.Format("select THIETBI_ID from THIETBI where MATHIETBI = '{0}'", _currMaThietBi)
            Dim thietbi_id As Object = MITI.BaseDB.ExecSql_DataValue(sql)
            Dim objThietBi_TramRow As ThietBiDataSet.THIETBI_TRAMRow = Me.ThietBiDataSet.THIETBI_TRAM.NewTHIETBI_TRAMRow()
            objThietBi_TramRow.THIETBI_ID = CType(thietbi_id, Integer)
            objThietBi_TramRow.TRAM_ID = _tramId
            ThietBiDataSet.THIETBI_TRAM.AddTHIETBI_TRAMRow(objThietBi_TramRow)
            THIETBITRAMBindingSource.EndEdit()
            THIETBI_TRAMTableAdapter.Update(ThietBiDataSet.THIETBI_TRAM)
        End If
    End Sub

    Private Sub DataGridViewThietBi_Tram_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridViewThietBi_Tram.CellDoubleClick
        If DataGridViewThietBi_Tram.Columns(e.ColumnIndex).Name = "DVQL_ID" Then
            Dim frm As New frmDVQL
            frm.ShowDialog()
            If Not String.IsNullOrEmpty(frm.SelectedValue) Then
                Dim index As Integer = DONVIBindingSource.Find("MADONVI", CType(frm.SelectedValue, Object))
                DataGridViewThietBi_Tram.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = ThietBiDataSet.DONVI.Rows(index)("DONVI_ID")
            Else
                DataGridViewThietBi_Tram.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = DBNull.Value
            End If
            
        End If
    End Sub

    Private Sub DataGridViewThietBi_Tram_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridViewThietBi_Tram.KeyDown
        If e.KeyCode = Keys.Delete Then
            If MessageBox.Show("Muốn xóa thiết bị này?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                DataGridViewThietBi_Tram.Rows.Remove(DataGridViewThietBi_Tram.CurrentRow)
            End If
        End If
    End Sub
End Class